package com.liy.framework.web.rs.resource;

import com.liy.framework.common.dao.IBaseDao;
import com.liy.framework.common.extvo.ResultVO;
import com.liy.framework.common.utils.Tools;
import com.liy.framework.common.vo.BaseVO;
import com.liy.framework.web.rs.utils.ParamValidator;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Produces({"application/json;charset=UTF-8"})
public class CrudResource<Entity extends BaseVO<String>, BaseDao extends IBaseDao<Entity, String>> extends QueryResource<Entity, BaseDao> implements ICrudResource<Entity> {

    protected static Logger log = LoggerFactory.getLogger(CrudResource.class);

    protected ResultVO beforeAdd(Entity entity) throws Exception {
        return entity == null ? ParamValidator.fail("参数不能为空！") : ParamValidator.success();
    }

    protected ResultVO beforeUpdate(Entity entity) throws Exception {
        if (entity == null) {
            return ParamValidator.fail("参数不能为空！");
        } else {
            return Tools.StringIsNullOrSpace(entity.getId()) ? ParamValidator.fail("参数[id]不能为空！") : ParamValidator.success();
        }
    }

    @POST
    @Path("add")
    @Consumes({"application/json;charset=UTF-8"})
    public Response add(Entity entity) throws Exception {
        ResultVO resultVO = this.beforeAdd(entity);
        if (!resultVO.isSuccess()) {
            return this.buildResponse(resultVO);
        } else {
            if (Tools.StringIsNullOrSpace(entity.getId())) {
                entity.setId(Tools.getNewUUID());
            }

            int i = this.baseDao.insertSelective(entity);
            resultVO.setSuccess(i > 0);
            resultVO.setMessage(resultVO.isSuccess() ? "新增成功." : "新增失败.");
            return this.buildResponse(resultVO);
        }
    }

    @PUT
    @Path("update")
    @Consumes({"application/json;charset=UTF-8"})
    public Response update(Entity entity) throws Exception {
        ResultVO resultVO = this.beforeUpdate(entity);
        if (!resultVO.isSuccess()) {
            return this.buildResponse(resultVO);
        } else {
            int i = this.baseDao.updateByPrimaryKeySelective(entity);
            resultVO.setSuccess(i > 0);
            resultVO.setMessage(resultVO.isSuccess() ? "保存成功." : "保存失败.");
            return this.buildResponse(resultVO);
        }
    }

    @DELETE
    @Path("del/{id}")
    public Response delete(@PathParam("id") String id) throws Exception {
        if (Tools.StringIsNullOrSpace(id)) {
            return this.buildResponse(new ResultVO(false, "参数不能为空."));
        } else {
            this.baseDao.deleteByPrimaryKey(id);
            return this.buildResponse(new ResultVO(true, "删除成功."));
        }
    }
}
